package linkExcel;

import linkExcel.utils.ExcelUtils;
import linkExcel.utils.ToolUtils;
import linkExcel.vo.ExcelVo;
import org.apache.poi.common.usermodel.HyperlinkType;
import org.apache.poi.ss.usermodel.*;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 针对目标文件夹下所有文件保存至一个sheet
 */
public class WorkFilesMain {

    private static final String EXCEL_PATH = "E:\\引绰济辽\\_目录台账.xlsx";
    private static final String SHEET_NAME = "引绰济辽工作目录台账";
    private static final String BEGIN_PATH = "E:\\引绰济辽";

    private static List<String> ERROR_ITEMS = new ArrayList<>();

    private static Integer FILE_NUMS = 0;

    private static Integer DIRECTORY_NUMS = 0;

    private static Integer ROW_INDEX = 0;

    public static void main(String[] args) {
        //删除Excel
        ExcelUtils.delExcel(EXCEL_PATH);
        //打开或创建Excel
        Workbook workbook = ExcelUtils.createOrGetExcel(EXCEL_PATH, SHEET_NAME);
        //创建或选择sheet
        Sheet sheet = ExcelUtils.createOrGetSheet(workbook, SHEET_NAME);
        //遍历所有文件
        File file = new File(BEGIN_PATH);
        traverseFolder(file, 0, sheet, workbook);
        //打印错误结果
        System.out.println("共计[" + (DIRECTORY_NUMS + FILE_NUMS - ERROR_ITEMS.size()) + "/" + (DIRECTORY_NUMS + FILE_NUMS) + "]条。" + (ERROR_ITEMS.isEmpty() ? "超链加注全部成功" : "部分超链加注失败，失败内容如下"));
        if (!ERROR_ITEMS.isEmpty()) {
            ERROR_ITEMS.forEach(System.out::println);
        }
        //存入Excel保存
        ExcelUtils.saveExcel(workbook, EXCEL_PATH);
    }

    /**
     * 遍历文件夹下的所有文件
     *
     * @param folder   文件（夹）
     * @param colIndex
     * @param sheet
     * @param workbook
     * @return 文件vo对象集合
     */
    private static void traverseFolder(File folder, int colIndex, Sheet sheet, Workbook workbook) {
        //先做链接
        StringBuilder preStr = new StringBuilder();
        for (int i = 0; i < colIndex; i++) {
            if (i < colIndex - 1) {
                preStr.append("         ");
            } else if (i == colIndex - 1) {
                if (folder.isDirectory()) {
                    preStr.append(" ▼");
                } else {
                    preStr.append("🟠 ");
                }

            }
        }
        Row dataRow = sheet.createRow(ROW_INDEX++);
        sheet.setColumnWidth(0, 200 * 256);
        dataRow.createCell(0).setCellValue(preStr + folder.getName()+(folder.isDirectory()?"":(" ["+ToolUtils.formatFileSize(folder.length())+"]")));
        CreationHelper creationHelper = workbook.getCreationHelper();
        Hyperlink hyperlink = creationHelper.createHyperlink(HyperlinkType.URL);
        try {
            hyperlink.setAddress(ToolUtils.getRelativePath(folder.getPath(), EXCEL_PATH));
            dataRow.getCell(0).setHyperlink(hyperlink);
            //样式
            CellStyle cellStyle = dataRow.getCell(0).getCellStyle();
            CellStyle newStyle = workbook.createCellStyle();
            newStyle.cloneStyleFrom(cellStyle);
            Font font = workbook.createFont();
            font.setColor(folder.isDirectory() ? IndexedColors.BLUE.getIndex() : IndexedColors.ORANGE.getIndex());
            newStyle.setFont(font);
            dataRow.getCell(0).setCellStyle(newStyle);
        } catch (Exception e) {
            ERROR_ITEMS.add(folder.getPath() + "--" + e.getCause());
        }
        //再递归
        if (folder.isDirectory()) {
            DIRECTORY_NUMS++;
            System.out.println("\uD83D\uDFE0文件夹：【" + folder.getName() + "】");
            // 获取文件夹内的文件和子文件夹
            File[] subFiles = folder.listFiles();
            if (subFiles != null) {
                for (File file : subFiles) {
                    // 递归遍历子文件夹（父级的父级是“1.部门工作”就不再往下遍历了）
                    if (folder.getParentFile().getParentFile()!=null && folder.getParentFile().getParentFile().getName().equals("1.部门工作")) {
                        continue;
                    }
                    if (file.getName().startsWith("~$") || file.getName().startsWith("~WRL") || file.isHidden()){
                        continue;
                    }
                    if (file.getName().equals("jre")){
                        continue;
                    }
                    traverseFolder(file, colIndex + 1, sheet, workbook);
                }
            }
        } else {
            FILE_NUMS++;
        }
    }
}
